package com.elitel.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义 HttpServletRequest包装类
 */
public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper {
    Map<String, String[]> paramMap = new HashMap<>();
    private Map<String, String> params = new HashMap<>();

    public CustomHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        paramMap.putAll(request.getParameterMap());
        // 初始化 原先的参数
        initParams(request);
    }

    /**
     * 重写HttpServletRequestWrapper.getParameterMap方法
     *
     * @return
     */
    @Override
    public Map<String, String[]> getParameterMap() {
        return paramMap;
    }


    private void initParams(HttpServletRequest request) {
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            params.put(paramName, request.getParameter(paramName));
        }
    }

    @Override
    public String getParameter(String name) {
        return params.get(name);
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(params.keySet());
    }

    @Override
    public String[] getParameterValues(String name) {
        return new String[]{params.get(name)};
    }

    public String setParameter(String name, String val) {
        return params.put(name, val);
    }


}
